//
//  ErrorCorrectionViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/7.
//

#import "ErrorCorrectionViewController.h"
#import "UITextView+Placeholder.h"
#import "ExamQuestionErrorManager.h"
#import "FileUploadManager.h"

@interface ErrorCorrectionViewController()<JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UILabel *tipLabel;
@property(nonatomic,strong)UITextView *textView;
@property(nonatomic,strong)UILabel *countLabel;
@property(nonatomic,strong)UIView *picView;
@property(nonatomic,strong)UIView *addView;
@property(nonatomic,strong)NSMutableArray *selectArr;
@property(nonatomic,strong)NSMutableArray *photoArr;
@property(nonatomic,strong)ExamQuestionErrorManager *errorManager;
@property(nonatomic,strong)FileUploadManager *uploadManager;
@property(nonatomic,strong)JPProgressHUD *hud;
@property(nonatomic,strong)NSMutableArray *picArr;
@property(nonatomic,strong)UIImageView *logoImageView;
@property(nonatomic,strong)UILabel *picTitleLabel;

@end

@implementation ErrorCorrectionViewController

-(NSMutableArray *)selectArr{
    if(!_selectArr){
        _selectArr = [NSMutableArray array];
    }
    return _selectArr;
}

-(NSMutableArray *)photoArr{
    if(!_photoArr){
        _photoArr = [NSMutableArray array];
    }
    return _photoArr;
}

-(ExamQuestionErrorManager *)errorManager{
    if(!_errorManager){
        _errorManager = [[ExamQuestionErrorManager alloc]init];
        _errorManager.delegate = self;
    }
    return _errorManager;
}

-(FileUploadManager *)uploadManager{
    if(!_uploadManager){
        _uploadManager = [[FileUploadManager alloc]init];
        _uploadManager.delegate = self;
    }
    return _uploadManager;
}

-(NSMutableArray *)picArr{
    if(!_picArr){
        _picArr = [NSMutableArray array];
    }
    return _picArr;
}


- (void)viewDidLoad{
    [super viewDidLoad];
    [self createUI];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self popGestureClose];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self popGestureOpen];
}


#pragma mark - 返回
-(void)defaultBackSet{
    [self.customNavigationBar setLeftItemWithIcon:[UIImage imageNamed:@"nav_back_logo"]];
    [self.customNavigationBar.leftButton addTarget:self action:@selector(__backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)__backButtonClicked:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
    if(_blackBlock){
        _blackBlock();
    }
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.customNavigationBar setTitle:@"纠错"];
    
    UIButton *commitBtn = [[UIButton alloc]init];
    [commitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [commitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    commitBtn.titleLabel.font = JPUIFontPingFangSCMedium(14);
    commitBtn.backgroundColor = KThemeColor;
    commitBtn.layer.cornerRadius = 6;
    commitBtn.layer.masksToBounds = YES;
    commitBtn.ym_acceptEventInterval = 2.0;
    [commitBtn addTarget:self action:@selector(commitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customNavigationBar addSubview:commitBtn];
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(@40);
        make.height.mas_equalTo(@24);
        make.right.mas_equalTo(@-16);
        make.bottom.mas_equalTo(@-10);
    }];
    
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.font = JPUIFontPingFangSCMedium(17);
    self.titleLabel.textColor = KFontBlackColor;
    self.titleLabel.numberOfLines = 0;
    if(self.type == 1){
        self.titleLabel.text = self.questionModel.paperName?self.questionModel.paperName:@"";
    }else{
        self.titleLabel.text = self.paperModel.name?self.paperModel.name:@"";
    }
    [self.view addSubview:self.titleLabel];
    CGSize t_size = [self.titleLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-32,MAXFLOAT)];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+25);
        make.height.mas_equalTo(t_size.height);
    }];
    
    __weak typeof(self)self_weak_ = self;
    self.tipLabel = [[UILabel alloc]init];
    self.tipLabel.font = JPUIFontPingFangSCRegular(16);
    self.tipLabel.textColor = KFontGrayColor;
//    if([self.questionModel.type isEqualToString:@"36"]){
//        self.tipLabel.text = [NSString stringWithFormat:@"问题%@",self.questionModel.bsort];
//    }else{
//        self.tipLabel.text = [NSString stringWithFormat:@"问题%@-%@小题",self.questionModel.bsort,self.questionModel.lsort];
//    }
    self.tipLabel.text = [NSString stringWithFormat:@"问题%@",self.questionModel.sortId];
    [self.view addSubview:self.tipLabel];
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.height.mas_equalTo(@22);
        make.right.mas_equalTo(@-16);
        make.top.mas_equalTo(self_weak_.titleLabel.mas_bottom).offset(10);
    }];
    
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = KLineColor;
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        make.height.mas_equalTo(@1);
        make.top.mas_equalTo(self_weak_.tipLabel.mas_bottom).offset(16);
    }];
    
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = KbgColor;
    bgView.layer.cornerRadius = 10;
    bgView.layer.masksToBounds = YES;
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(line.mas_bottom).offset(16);
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        make.height.mas_equalTo(@166);
    }];
    
    self.textView = [[UITextView alloc]init];
    self.textView.backgroundColor = KbgColor;
    self.textView.font = JPUIFontPingFangSCRegular(15);
    self.textView.textColor = KFontGrayColor;
    self.textView.tintColor = KThemeColor;
    [self.textView setPlaceholder:@"请输入您遇到的问题，也可以添加图片..." placeholdColor:KFontGrayColor];
    self.textView.contentInset = UIEdgeInsetsZero;
    self.textView.textContainerInset = UIEdgeInsetsZero;
    [bgView addSubview:self.textView];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@13);
        make.right.mas_equalTo(@-13);
        make.bottom.mas_equalTo(-45);
        make.top.mas_equalTo(@16);
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChangeText:) name:UITextViewTextDidChangeNotification object:self.textView];
    
    self.countLabel = [[UILabel alloc]init];
    self.countLabel.font = JPUIFontPingFangSCRegular(15);
    self.countLabel.textColor = KFontGrayColor;
    self.countLabel.textAlignment = NSTextAlignmentRight;
    self.countLabel.text = @"0/200";
    [bgView addSubview:self.countLabel];
    [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(@-12);
        make.height.mas_equalTo(@21);
        make.bottom.mas_equalTo(@-12);
    }];
    CGFloat pic_w = [DeviceUtils getAdaptedWidthForDesignWidth:92 andCurrentAvailableWidth:self.currentAvailableWidth];
    self.picView = [[UIView alloc]init];
    self.picView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.picView];
    [self.picView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(bgView.mas_bottom).offset(16);
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        make.height.mas_equalTo(pic_w);
    }];
    CGFloat pic_left = 0;
    CGFloat pic_mid = (self.currentAvailableWidth-32-pic_w*3)/2.0;
    for (NSInteger i = 0; i < 3;i++) {
        UIImageView *picImageView = [[UIImageView alloc]init];
        picImageView.layer.cornerRadius = 10;
        picImageView.layer.masksToBounds = YES;
        picImageView.userInteractionEnabled = YES;
        picImageView.tag = 666+i;
        [self.picView addSubview:picImageView];
        [picImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(pic_left);
            make.width.height.mas_equalTo(pic_w);
            make.top.mas_equalTo(@0);
        }];
        pic_left = pic_left+pic_w+pic_mid;
        UITapGestureRecognizer *pictap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
            [self_weak_ choosePhoto];
        }];
        [picImageView addGestureRecognizer:pictap];
        picImageView.hidden = YES;
    }
    
    self.addView = [[UIView alloc]init];
    self.addView.backgroundColor = KbgColor;
    self.addView.layer.cornerRadius = 10;
    self.addView.layer.masksToBounds = YES;
    [self.picView addSubview:self.addView];
    [self.addView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@0);
        make.width.height.mas_equalTo(pic_w);
        make.top.mas_equalTo(@0);
    }];
    UITapGestureRecognizer *addtap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
        [self_weak_ choosePhoto];
    }];
    [self.addView addGestureRecognizer:addtap];
    CGFloat w30 = [DeviceUtils getAdaptedWidthForDesignWidth:30 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w18 = [DeviceUtils getAdaptedWidthForDesignWidth:18 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w5 = [DeviceUtils getAdaptedWidthForDesignWidth:5 andCurrentAvailableWidth:self.currentAvailableWidth];

    UIImageView *logoImageView = [[UIImageView alloc]init];
    logoImageView.image = [UIImage imageNamed:@"add_pic_logo"];
    logoImageView.userInteractionEnabled = YES;
    [self.addView addSubview:logoImageView];
    [logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(w30);
        make.top.mas_equalTo(w18);
        make.centerX.mas_equalTo(self_weak_.addView);
    }];
    self.logoImageView = logoImageView;
    
    UILabel *picTitleLabel = [[UILabel alloc]init];
    picTitleLabel.font = JPUIFontPingFangSCRegular(15);
    picTitleLabel.textColor = KFontGrayColor;
    picTitleLabel.textAlignment = NSTextAlignmentCenter;
    picTitleLabel.userInteractionEnabled = YES;
    picTitleLabel.text = @"添加图片";
    [self.addView addSubview:picTitleLabel];
    [picTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@21);
        make.top.mas_equalTo(logoImageView.mas_bottom).offset(w5);
        make.left.right.mas_equalTo(@0);
    }];
    self.picTitleLabel = picTitleLabel;
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            CGFloat pic_w = [DeviceUtils getAdaptedWidthForDesignWidth:92 andCurrentAvailableWidth:self.currentAvailableWidth];
            [self.picView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(pic_w);
            }];
            CGFloat pic_left = 0;
            CGFloat pic_mid = (self.currentAvailableWidth-32-pic_w*3)/2.0;
            for (NSInteger i = 0; i < 3;i++) {
                UIImageView *picImageView = [self.picView viewWithTag:666+i];
                [picImageView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(pic_left);
                    make.width.height.mas_equalTo(pic_w);
                }];
                pic_left = pic_left+pic_w+pic_mid;
            }
            [self.addView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.height.mas_equalTo(pic_w);
            }];
            CGFloat w30 = [DeviceUtils getAdaptedWidthForDesignWidth:30 andCurrentAvailableWidth:self.currentAvailableWidth];
            CGFloat w18 = [DeviceUtils getAdaptedWidthForDesignWidth:18 andCurrentAvailableWidth:self.currentAvailableWidth];
            CGFloat w5 = [DeviceUtils getAdaptedWidthForDesignWidth:5 andCurrentAvailableWidth:self.currentAvailableWidth];
            [self.logoImageView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.height.mas_equalTo(w30);
                make.top.mas_equalTo(w18);
            }];
            __weak typeof(self)self_weak_ = self;
            [self.picTitleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self_weak_.logoImageView.mas_bottom).offset(w5);
            }];
            
        });
    }
}

#pragma mark - 点击选择图片
-(void)choosePhoto{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted||status == PHAuthorizationStatusDenied){
         //无权限
        [JPProgressHUD showMsg:@"无权限访问相册，请去设置页面打开访问权限"];
         return ;
    }else if (status == PHAuthorizationStatusNotDetermined){
         //第一次进来还没有选择是否授权
         [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
             dispatch_async(dispatch_get_main_queue(), ^{
                 if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied){
                     // 用户拒绝，跳转到自定义提示页面
                     [JPProgressHUD showMsg:@"无权限访问相册，请去设置页面打开访问权限"];
                 }else if (status == PHAuthorizationStatusAuthorized){
                     // 用户授权，弹出相册对话框
                     [self addPic];
                 }
             });
         }];
         return;
    }else{
        // 用户授权，弹出相册对话框
        [self addPic];
    }
}


#pragma mark - 添加图片
-(void)addPic{
    __weak typeof(self)self_weak_ = self;
    ZLPhotoPreviewSheet *ac = [[ZLPhotoPreviewSheet alloc]initWithSelectedAssets:self.selectArr];
    ZLPhotoConfiguration *configuration = [ZLPhotoConfiguration default];
    configuration.allowSelectVideo = NO;
    configuration.maxSelectCount = 3;
    configuration.allowSelectGif = NO;
    [configuration.editImageConfiguration setClipRatios:@[[ZLImageClipRatio custom]]];
    configuration.editAfterSelectThumbnailImage = NO;
//    configuration.showClipDirectlyIfOnlyHasClipTool = NO;
    [configuration.editImageConfiguration setTools_objc:@[@(EditToolDraw),@(EditToolClip),@(EditToolImageSticker),@(EditToolTextSticker),@(EditToolMosaic),@(EditToolFilter),@(EditToolAdjust)]];
    ac.selectImageBlock = ^(NSArray<ZLPhotoModel *> *results, BOOL isOriginal) {
        [self_weak_.selectArr removeAllObjects];
        [self_weak_.selectArr addObjectsFromArray:[results valueForKeyPath:@"asset"]];
        [self_weak_.photoArr removeAllObjects];
        [self_weak_.photoArr addObjectsFromArray:[results valueForKeyPath:@"image"]];
        //刷新界面
        [self_weak_ refreshPicUI];
      };

//      ac.cancelBlock = ^{
//          NSLog(@"cancel select");
//      };

      [ac showPhotoLibraryWithSender:self];
}

#pragma mark - 图片界面刷新
-(void)refreshPicUI{
    CGFloat left = 0;
    CGFloat pic_w = [DeviceUtils getAdaptedWidthForDesignWidth:92 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat pic_mid = (self.currentAvailableWidth-32-pic_w*3)/2.0;
    for (NSInteger i = 0; i < 3;i++) {
        UIImageView *picImageView = [self.picView viewWithTag:666+i];
        if(i < self.photoArr.count){
            picImageView.hidden = NO;
            picImageView.image = self.photoArr[i];
            left = left+pic_w+pic_mid;
        }else{
            picImageView.hidden = YES;
        }
    }
    if(self.selectArr.count == 3){
        self.addView.hidden = YES;
    }else{
        self.addView.hidden = NO;
        [self.addView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(left);
        }];
    }
}

#pragma mark - 监测用户输入文本长度
- (void)textViewDidChangeText:(NSNotification *)notification{

   //最大输入长度,中英文字符都按一个字符计算
    static int kMaxLength = 200;
    UITextView *textView = (UITextView *)notification.object;
    NSString *toBeString = textView.text;
     // 获取键盘输入模式
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage];
    // 中文输入的时候,可能有markedText(高亮选择的文字),需要判断这种状态
    // zh-Hans表示简体中文输入, 包括简体拼音，健体五笔，简体手写
    if ([lang isEqualToString:@"zh-Hans"]) {
        UITextRange *selectedRange = [textView markedTextRange];
        //获取高亮选择部分
        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，表明输入结束,则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > kMaxLength) {
                // 截取子串
                textView.text = [toBeString substringToIndex:kMaxLength];
            }
        }
    } else {
        // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        if (toBeString.length > kMaxLength) {
            // 截取子串
            textView.text = [toBeString substringToIndex:kMaxLength];
        }
    }
    self.countLabel.text = [NSString stringWithFormat:@"%ld/200",textView.text.length>200?200:textView.text.length];
}

#pragma mark - 提交
-(void)commitBtnClick{
    
    [self.textView resignFirstResponder];
    [self.picArr removeAllObjects];
    
    //先上传图片
    if(self.textView.text.length == 0){
        [JPProgressHUD showMsg:@"请输入您遇到的问题"];
        return;
    }
    if(self.photoArr.count == 0){
        [JPProgressHUD showMsg:@"请选择图片"];
        return;
    }
    
    self.hud = [JPProgressHUD showLoading];
    
    [self uploadWithImage:self.photoArr[0]];
   
}

-(void)commitError{
    
    self.errorManager.paperName = self.paperModel?self.paperModel.name:@"";
    self.errorManager.questionName = self.textView.text;
    NSMutableString *pstr = [NSMutableString string];
    for(NSInteger i = 0;i < self.picArr.count;i++){
        NSString *str = self.picArr[i];
        [pstr appendString:str];
        if(i != self.picArr.count-1){
            [pstr appendString:@","];
        }
    }
    self.errorManager.paths = pstr;
    self.errorManager.sortId = self.questionModel.sortId?self.questionModel.sortId:@"";
    [self.errorManager loadData];
    
}

#pragma mark - 图片上传
-(void)uploadWithImage:(UIImage*)sendImage{
    NSData *data = UIImageJPEGRepresentation(sendImage,0.5);
    NSInteger timeStamp = [[NSNumber numberWithDouble:
                            [[NSDate date] timeIntervalSince1970]] integerValue];
    NSString *path = NSTemporaryDirectory();
    NSString *fileName = [NSString stringWithFormat: @"%li_exam_error.jpeg",timeStamp];
    NSString *urlstr = [NSString stringWithFormat: @"%@/%@",path,fileName];
    NSURL *url = [NSURL fileURLWithPath:urlstr];
    [data writeToURL:url atomically:YES];
    [self.uploadManager setFile:url];
    [self.uploadManager loadData];
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.uploadManager]){
        NSDictionary *dic = manager.response.content;
        NSString *picUrl = [NSString stringWithFormat:@"%@",dic[@"data"][@"url"]];
        [self.picArr addObject:picUrl];
        if(self.picArr.count < self.photoArr.count){
            [self uploadWithImage:self.photoArr[self.picArr.count]];
        }else{
            //上传完 提交
            [self commitError];
        }
    }
    
    if([manager isEqual:self.errorManager]){
        NSDictionary *dic = manager.response.content;
        if(self.hud){
            [self.hud removeFromSuperview];
        }
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        [self.navigationController popViewControllerAnimated:YES];
        if(_blackBlock){
            _blackBlock();
        }
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.uploadManager]||[manager isEqual:self.errorManager]){
        [self.picArr removeAllObjects];
    }
    if(self.hud){
        [self.hud removeFromSuperview];
    }
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}



@end
